layui.config({
    base : "../static/js/"
}).extend({
    "address" : "orderaddress"
})
layui.use(['form','layer','table','jquery','address','treeSelect','tablePlug'],function(){
    var form = layui.form
        layer = layui.layer,
        player = parent.layui.layer,
        table = layui.table,
        $ = layui.jquery,
        tablePlug = layui.tablePlug,
       address = layui.address;
    
    //获取省信息
    address.provinces();
    
  //企业列表
    var tableIns = table.render({
        elem: '#gridList',
        method: 'post',
//        url : '../task/enterpriseGrid?primaryP='+$('#primaryP').val()+'&hotP='+$('#hotP').val(),
        cellMinWidth : 100,
        page : true,
        height : "750",
        limits : [10,15,20,25],
        limit : 20,
        initSort: {
            field: 'id' //排序字段，对应 cols 设定的各字段名
            ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        id : "gridListTable",
        done: function () {
            var tableView = this.elem.next();
            var totalRow = tableView.find('.layui-table-total');
            var limit = this.page ? this.page.limit : this.limit;
            layui.each(totalRow.find('td'), function (index, tdElem) {
              tdElem = $(tdElem);
              var text = tdElem.text();
              if (text && !isNaN(text)) {
                text = (parseFloat(text) / limit).toFixed(2);
                tdElem.find('div.layui-table-cell').html(text);
              }
            });
          },
        checkStatus: {
       	 primaryKey: 'id'
        },
        cols : [[
        	{type:'checkbox'},
            {field: 'id', title: '序号', minWidth:50, align:"center"},
            {field: 'province', title: '省份', minWidth:50, align:"center"},
            {field: 'cityName', title: '地市名称', minWidth:50, align:"center"},
            {field: 'companyName', title: '公司名称', minWidth:100, align:"center"},
            {field: 'industry', minWidth:100, title: '行业', align:'center'},
            {field: 'state', minWidth:50, title: '状态', align:'center'},
            {field: 'legal', minWidth:50, title: '法人', align:'center'},
            {field: 'registered', minWidth:50, title: '注册资本', align:'center'},
            {field: 'telephone', minWidth:50, title: '联系电话', align:'center'},
            {field: 'address', minWidth:100, title: '企业地址',  align:'center'},
            {field: 'website', minWidth:100, title: '企业网址',  align:'center'},
            {field: 'email', minWidth:80, title: '企业邮箱',  align:'center'},
            {field: 'develop', minWidth:80, title: '发展状态',  align:'center'},
            {field: 'scope', minWidth:100, title: '经营范围',  align:'center'}           
        ]]
    });
    
    form.on('switch(isAll)', function(data){
    	  if(this.checked){
    		  $("#isAll").val('true');
    	  }else{
    	  }
    	}); 
    
    form.on('select(industry)', function(data){
    	if($("#product1").val() && $("#product2").val()){
	    	var industry = $("#industry").find("option:selected").text();
			form.render('select'); //这个很重要
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8,offset: ['300px', '500px']});
	    	setTimeout(function(){
	    		table.reload("gridListTable",{
	    			url : '../task/enterpriseGrid',
	                page: {
	                    curr: 1 //重新从第 1 页开始
	                },
	                where: {
	                	"industry": industry,  //搜索的关键字
	                	"primaryP" : $('#primaryP').val(),
                        "hotP" : $('#hotP').val(),
                        "cityName" : $('#city')?$('#city').val():""
	                }
	            });
				layer.close(index);
			},2000);
    	}else{
    		$("#industry").val('');
    		form.render('select');
    		player.alert("请先选择主推产品及热推产品！");
    	}
	});
    
    form.on('select(develop)', function(data){
    	if($("#product1").val() && $("#product2").val()){    
			var develop = $("#develop").find("option:selected").val();
			form.render('select'); //这个很重要
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8,offset: ['300px', '500px']});
	    	setTimeout(function(){
	    		table.reload("gridListTable",{
	    			url : '../task/enterpriseGrid',
	                page: {
	                    curr: 1 //重新从第 1 页开始
	                },
	                where: {
	                	"develop": develop,  //搜索的关键字
	                	"primaryP" : $('#primaryP').val(),
                        "hotP" : $('#hotP').val(),
                        "cityName" : $('#city')?$('#city').val():""
	                }
	            });
				layer.close(index);
			},2000);
    	}else{
    		player.alert("请先选择主推产品及热推产品！");
    	}
	});
    
    form.on('select(type)', function(data){
    	if($("#product1").val() && $("#product2").val()){
	    	var type = $("#type").find("option:selected").text();
			form.render('select'); //这个很重要
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8,offset: ['300px', '500px']});
	    	setTimeout(function(){
	    		table.reload("gridListTable",{
	    			url : '../task/enterpriseGrid',
	                page: {
	                    curr: 1 //重新从第 1 页开始
	                },
	                where: {
	                	"type": type,  //搜索的关键字
	                	"primaryP" : $('#primaryP').val(),
                        "hotP" : $('#hotP').val(),
                        "cityName" : $('#city')?$('#city').val():""
	                }
	            });
				layer.close(index);
			},2000);
    	}else{
    		player.alert("请先选择主推产品及热推产品！");
    	}
	});
    
    form.on('select(scale)', function(data){
    	if($("#product1").val() && $("#product2").val()){
			var scale = $("#scale").find("option:selected").text();
			form.render('select'); //这个很重要
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8,offset: ['300px', '500px']});
	    	setTimeout(function(){
	    		table.reload("gridListTable",{
	    			url : '../task/enterpriseGrid',
	                page: {
	                    curr: 1 //重新从第 1 页开始
	                },
	                where: {
	                	"scale": scale,  //搜索的关键字
	                	"primaryP" : $('#primaryP').val(),
                        "hotP" : $('#hotP').val(),
                        "cityName" : $('#city')?$('#city').val():""
	                }
	            });
				layer.close(index);
			},2000);
    	}else{
    		player.alert("请先选择主推产品及热推产品！");
    	}
	});

    //搜索
    $(".search_btn").on("click",function(){
    	if($("#product1").val() && $("#product2").val()){
	    	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8,offset: ['300px', '500px']});
	        	setTimeout(function(){
	        		table.reload("gridListTable",{
	        			url : '../task/enterpriseGrid',
	                    page: {
	                        curr: 1 //重新从第 1 页开始
	                    },
	                    where: {
	                        "companyName" : $(".searchVal").val(),  //搜索的关键字
	                        "primaryP" : $('#primaryP').val(),
	                        "hotP" : $('#hotP').val(),
	                        "cityName" : $('#city')?$('#city').val():""
	                    }
	                });
	    			layer.close(index);
	    		},2000);
    	}else{
    		player.alert("请先选择主推产品及热推产品！");
    	}
    });
    
    table.on('checkbox(gridList)', function(obj){
   	 var checkStatus = table.checkStatus('gridListTable');
   	 console.log(checkStatus.data.additional);
 	});
    
    form.on("submit(addTask)",function(data){
    	var name = $("#name").val().trim();
    	var describe = $("#describe").val();
	 	var primaryP = $("#primaryP").val().trim();
	 	var hotP = $("#hotP").val().trim();
	 	var city = data.field.city;
    	var area = data.field.area;
	 	var enterpriseIds = table.checkStatus('gridListTable').data.additional;
	 	var orgId =  $("#orgId").val();
	 	var tableData = [];
	 	if(!$("#isAll").val()&&enterpriseIds.length==0){
	 		player.alert('请选择企业！');
	 	}else{
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
        	$.ajax({
    			type : "POST",
    			url : "../task/addBatch",
    			data : {
    				"name" : name,
    				"describe" : describe,
    				"primaryP" : primaryP,
    				"hotP" : hotP,
    				"enterpriseIds" : JSON.stringify(enterpriseIds),
    				"cityName" : city,
    				"area" : area,
    				"orgId" : orgId,
    				"companyName" : $(".searchVal").val(),
    				"type" : $("#type").find("option:selected").text(),
    				"develop" : $("#develop").find("option:selected").val(),
    				"industry" : $("#industry").find("option:selected").text(),
    				"scale" : $("#scale").find("option:selected").text(),
    				"isAll" : $("#isAll").val()
    			},
    			dataType : "json",
    			success : function(jsonObject) {
    				top.layer.close(index);
    	            top.layer.msg("任务添加成功！");
    	            layer.closeAll("iframe");
    	            //刷新父页面
    	            parent.location.reload();
    			}
    		});
        },2000);
        return false;
	 	}
    });
    
    var treeSelect= layui.treeSelect;

    treeSelect.render({
        // 选择器
        elem: '#orgId',
        // 数据
        data: '../organization/tree',
        // 异步加载方式：get/post，默认get
        type: 'post',
        // 占位符
        placeholder: '请选择执行部门',
        // 是否开启搜索功能：true/false，默认false
        search: true,
        // 点击回调
        click: function(d){
           console.log(d.current);
           $('#orgId').val(d.current.id)
        },
        // 加载完成后的回调函数
        success: function (d) {
            console.log(d);
        }
    });   
    
    //格式化时间
    function filterTime(val){
        if(val < 10){
            return "0" + val;
        }else{
            return val;
        }
    }
    //定时发布
    var time = new Date();
    var submitTime = time.getFullYear()+'-'+filterTime(time.getMonth()+1)+'-'+filterTime(time.getDate())+' '+filterTime(time.getHours())+':'+filterTime(time.getMinutes())+':'+filterTime(time.getSeconds());
    
    //添加产品
    function addProduct(flag){
    	var index = layui.layer.open({
            title : "产品列表",
            type : 2,
            area: ['1000px', '500px'],
            offset: ['100px', '50px'],
            fixed: false, //不固定
            maxmin: true,
            content : "../task/product",
            success : function(layero, index){
            	console.log(index);
                var body = layui.layer.getChildFrame('body', index);
                body.find('#flag').val(flag)
                setTimeout(function(){
                    layui.layer.tips('点击此处返回任务添加页面', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
    }
    
  //列表操作
    table.on('tool(gridList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
       if(layEvent === 'del'){ //删除
    	var olddata = table.cache.gridListTable;
    	olddata.splice(obj.tr.data('index'),1);
    	tableIns.reload({data:olddata});
        }
    });
    
    $(".resettable").focus(function(){
    	table.reload('gridListTable',{data:[]});
    })
    $("#product1").focus(function(){
    	addProduct("#product1");
    	$("#product1").blur();
    })
    $("#product2").focus(function(){
    	addProduct("#product2");
    	$("#product2").blur();
    })
    $(".addEnterprise_btn").click(function(){
    	if($("#product1").val() && $("#product2").val()){
    		addEnterprise();
    	}else{
    		layer.alert("请先选择主推产品及热推产品！");
    	}
    	
    })
})